package com.xinlan.imageeditlibrary.editimage.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.xinlan.imageeditlibrary.BaseEditFragment;
import com.xinlan.imageeditlibrary.EditImageFragment;
import com.xinlan.imageeditlibrary.R;
import com.xinlan.imageeditlibrary.editimage.ModuleConfig;
import com.xinlan.imageeditlibrary.editimage.adapter.TextColorSelectListAdapter;
import com.xinlan.imageeditlibrary.editimage.model.OnBackPressedCallBack;
import com.xinlan.imageeditlibrary.editimage.model.SpacesItemDecoration;
import com.xinlan.imageeditlibrary.editimage.model.TextColorListEnum;
import com.xinlan.imageeditlibrary.editimage.task.StickerTask;
import com.xinlan.imageeditlibrary.editimage.utils.BaseUtils;
import com.xinlan.imageeditlibrary.editimage.utils.DensityUtil;
import com.xinlan.imageeditlibrary.editimage.utils.InputTools;
import com.xinlan.imageeditlibrary.editimage.view.TextStickerView;


/**
 * 添加文本贴图
 *
 * @author 潘易
 */
public class AddTextFragment extends BaseEditFragment implements TextWatcher {
    public static final int INDEX = ModuleConfig.INDEX_ADDTEXT;
    public static final String TAG = AddTextFragment.class.getName();

    private View mainView;

    private EditText mInputText;//输入框
    private TextStickerView mTextStickerView;// 文字贴图显示控件


    private int mTextColor = Color.WHITE;
    private InputMethodManager imm;

    private SaveTextStickerTask mSaveTask;
    private EditImageFragment mEditImageFragment;
    private RecyclerView mRvColorSelect;
    private TextColorSelectListAdapter mColorSelectListAdapter;
    private OnBackPressedCallBack mOnBackCall;
    private View mPopAddTextView;
    private PopupWindow mPopAddText;

    private Handler tHandler = new Handler();

    public static AddTextFragment newInstance(EditImageFragment mEditImageFragment) {
        AddTextFragment fragment = new AddTextFragment();
        fragment.setEditImageFragment(mEditImageFragment);
        fragment.setOnBackClick();
        return fragment;
    }


    public OnBackPressedCallBack getOnBackCall() {
        return mOnBackCall;
    }

    public void setOnBackClick() {
        mOnBackCall = new OnBackPressedCallBack() {
            @Override
            public void onBack() {
                backToMain();
            }
        };
    }

    public void setEditImageFragment(EditImageFragment mEditImageFragment) {
        this.mEditImageFragment = mEditImageFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        imm = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mainView = inflater.inflate(R.layout.fragment_edit_image_add_text, null);
        return mainView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(mEditImageFragment!=null) {
            if(mEditImageFragment.mTextStickerView!=null) {
                this.mTextStickerView = mEditImageFragment.mTextStickerView;
            }
            initView();
            initListener();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void initView() {
        mPopAddTextView = getLayoutInflater().inflate(R.layout.popup_addtext, null);
        mPopAddText = BaseUtils.showPopwindow(activity, mPopAddTextView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mInputText = mPopAddTextView.findViewById(R.id.text_input);
        mRvColorSelect = mPopAddTextView.findViewById(R.id.rv_color_select);
        mTextStickerView.setEditText(mInputText);


        mTextStickerView.setTextColor(Color.parseColor("#8C00FF")); //设置默认颜色
        mColorSelectListAdapter = new TextColorSelectListAdapter(getLayoutInflater(), getContext());
        TextColorListEnum[] values = TextColorListEnum.values();
        mColorSelectListAdapter.setList(values);
        mRvColorSelect.setAdapter(mColorSelectListAdapter);
        mRvColorSelect.addItemDecoration(new SpacesItemDecoration(DensityUtil.dip2px(requireContext(), 30)));
        mPopAddTextView.findViewById(R.id.tv_hidepop).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopAddText.dismiss();
                InputTools.hideInput(activity);
                mEditImageFragment.mode = EditImageFragment.MODE_NONE;
                mEditImageFragment.mainImage.setVisibility(View.VISIBLE);
                mTextStickerView.setVisibility(View.VISIBLE);
                mEditImageFragment.swFragment(0);
            }
        });
        mTextStickerView.setOnSubmitTextClickListener(new TextStickerView.OnSubmitTextClickListener() {
            @Override
            public void onSubmitTextClick() {
                applyTextImage(null);
            }
        });
    }

    private void initListener() {
        mInputText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //InputTools.showInput(v);
            }
        });
        mInputText.addTextChangedListener(this);
        mColorSelectListAdapter.setOnTextColorClickListener(new TextColorSelectListAdapter.OnTextColorClickListener() {
            @Override
            public void onTextColorClick(TextColorListEnum textColorListBean) {

                changeTextColor(textColorListBean.getParseColor());
            }
        });
    }

    @Override
    public void afterTextChanged(Editable s) {
        String text = s.toString().trim();

        mTextStickerView.setText(text);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }


    /**
     * 修改字体颜色
     *
     * @param newColor
     */
    private void changeTextColor(int newColor) {
        this.mTextColor = newColor;
        mTextStickerView.setTextColor(mTextColor);
    }

    public void hideInput() {
        if (getActivity() != null && getActivity().getCurrentFocus() != null && isInputMethodShow()) {
            imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public boolean isInputMethodShow() {
        return imm.isActive();
    }

    /**
     * 返回主菜单
     */
    @Override
    public void backToMain() {
        hideInput();
        if (mPopAddText != null && mPopAddText.isShowing())
            mPopAddText.dismiss();
        mEditImageFragment.mode = EditImageFragment.MODE_NONE;
        mEditImageFragment.mainImage.setVisibility(View.VISIBLE);
        mTextStickerView.setVisibility(View.GONE);
        mEditImageFragment.swFragment(0);
    }

    @Override
    public void onShow() {
        mPopAddText.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
        mEditImageFragment.mode = EditImageFragment.MODE_TEXT;
        //mEditImageFragment.mainImage.setImageBitmap(mEditImageFragment.getMainBit());
        mTextStickerView.setVisibility(View.VISIBLE);
        mInputText.clearFocus();
        if (mTextStickerView != null)
            mTextStickerView.resetView();

        tHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) mInputText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                mInputText.setFocusable(true);
                mInputText.setFocusableInTouchMode(true);
                mInputText.requestFocus();
                mInputText.findFocus();
            }
        }, 100);

    }

    /**
     * 保存贴图图片
     */
    public void applyTextImage(BaseUtils.OnAddStickerAndText onAddStickerAndText) {
        if (TextUtils.isEmpty(mTextStickerView.getText())) {//没有进行操作
            if (onAddStickerAndText != null)
                onAddStickerAndText.onAddStickerAndText(0);
            return;
        }
        if (mSaveTask != null) {
            mSaveTask.cancel(true);
        }

        //启动任务
        mSaveTask = new SaveTextStickerTask(mEditImageFragment, onAddStickerAndText);
        mSaveTask.execute(mEditImageFragment.getMainBit());
    }

    /**
     * 文字合成任务
     * 合成最终图片
     */
    private final class SaveTextStickerTask extends StickerTask {
        private BaseUtils.OnAddStickerAndText onAddStickerAndText;

        public SaveTextStickerTask(EditImageFragment activity, BaseUtils.OnAddStickerAndText onAddStickerAndText) {
            super(activity);
            this.onAddStickerAndText = onAddStickerAndText;
        }

        @Override
        public void handleImage(Canvas canvas, Matrix m) {
            float[] f = new float[9];
            m.getValues(f);
            int dx = (int) f[Matrix.MTRANS_X];
            int dy = (int) f[Matrix.MTRANS_Y];
            float scale_x = f[Matrix.MSCALE_X];
            float scale_y = f[Matrix.MSCALE_Y];
            canvas.save();
            canvas.translate(dx, dy);
            canvas.scale(scale_x, scale_y);
            //System.out.println("scale = " + scale_x + "       " + scale_y + "     " + dx + "    " + dy);
            mTextStickerView.drawText(canvas, mTextStickerView.layout_x,
                    mTextStickerView.layout_y, mTextStickerView.mScale, mTextStickerView.mRotateAngle);
            canvas.restore();
        }

        @Override
        public void onPostResult(Bitmap result) {
            mTextStickerView.clearTextContent();
            mTextStickerView.resetView();

            mEditImageFragment.changeMainBitmap(result, true);
            backToMain();
            if (onAddStickerAndText != null)
                onAddStickerAndText.onAddStickerAndText(0);
        }
    }//end inner class

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSaveTask != null && !mSaveTask.isCancelled()) {
            mSaveTask.cancel(true);
        }
    }
}// end class
